﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
    <link href="../css/quote2.css" rel="stylesheet" type="text/css" />
    <style>
        body
        {
            font-size: 11px;
            font-family: tahoma;
        }
        input
        {
            font-size: 11px;
        }
        .inputTxt
        {
            width: 80px;
            border-color: #6B6B6B #B9B9B9 #DDDDDD;
            border-style: solid;
            border-width: 1px;
            color: #333333;
            display: inline;
            font-size: 93%;
            margin: 4px 5px 0;
            padding: 2px 0 2px 2px;
        }
        .btn
        {
            background-color: #FFFFFF;
            border-color: #6B6B6B #B9B9B9 #DDDDDD;
            border-style: solid;
            border-width: 1px;
            color: #333333;
            display: inline;
            margin: 4px 5px 0 -1px;
            padding: 2px 4px;
            text-decoration: none;width:auto;}
        .ctrtable td
        {
            border-left: 1px solid #999999;
            border-right: 1px solid #999999;
            border-bottom: 1px solid #999999;
            padding: 2px 10px;
            height:25px;
        }
    </style>
     <script type="text/javascript"src="../lib//jquery.js"></script>
    <script src="../lib/migratory-jslib.js" type="text/javascript"></script>
    <script src="../js/ui/util.js" type="text/javascript"></script>
</head>
<body>
    <div style="width: 100%; float: left;">
        <table class="ctrtable"  cellpadding=0 cellspacing= 0>
            <tr>
                <td>
                    <input id="ticker" class="inputTxt" />
                    <input type="button" value="Subscrib ticker" onclick="subscribeTicker()" class="btn" />
                </td>
                <td>
                <input id="unTicker" class="inputTxt" />
                <input type="button" value="Unsubscrib ticker" onclick="unsubscribeTicker()" class="btn" />
                </td>
                <td><div class="ddlType"></div></td><td><div class="ddlServer"></div></td>
            </tr>
            <tr><td>Symbol</td><td>Last Price</td><td>Volume</td><td>Time</td></tr>
        </table>
    </div>
</body>
<script>
var p;
var stype = "1";
var typeList = [{txt:"Stock",val:"1"},{txt:"Option",val:"2"},{txt:"Index",val:"10"}];
var serverList=[{txt:"Dev",val:"http://pushdev.morningstar.com"},{txt:"Live",val:"http://push.morningstar.com"}]
var tab = $(".ctrtable");
var pushServer = "http://pushdev.morningstar.com";
var ddlType = new Util.DropDownList($(".ddlType")[0], function(k,v){stype = v;}, typeList, {triggerByClick:false, width:75,disable:false, actionAtInit:false});
function addNewRow(symbol){
    var str = '<tr id ='+symbol+'><td>'+symbol+'</td><td id ="'+symbol+'LastPrice"></td><td id ="'+symbol+'Volume"></td>';
    str += '<td id ="'+symbol+'Time"></td></tr>';
    return str;
}
function removeRow(symbol) {
    $("#"+symbol).remove();
}
function subscribeTicker() {
    var t = document.getElementById("ticker").value;
    var tt = t.split(":");
    var sourceType = "D";
    var serviceName = tt[0];
    var item = stype+"_"+tt[1]+"_-1";
    p.subscribe(operationHandler, "subscribeClosure",sourceType,serviceName,item);
    tab.append(addNewRow(tt[1]));
}
function unsubscribeTicker() {
    var t = document.getElementById("unTicker").value;
    var tt = t.split(":");
    var sourceType = "D";
    var serviceName = tt[0];
    var item = stype+"_"+tt[1]+"_-1";
    p.unsubscribe(operationHandler, "subscribeClosure",sourceType,serviceName,item);
    removeRow(tt[1]);
}
function init() 
{
	// Connecting to the server.
	// If the operation is successful the "operationHandler" will be notified with an "jslib.OPERATION_OK" event type,
	// if the operation fails then the "operationHandler" will be notified with an "jslib.OPERATION_ERROR" event type.
	// The second parameter, "connectClosure" is an arbitrary object that can be passed to this function (closure),
	// when notifying the "operationHandler" you will also receive this object. This allows to reuse an operation handler for
	// more than one jslib operation. You should specify unique closures for every operation, this way you can uniquely identify
	// which operation is the cause of a notification in the operationHandler. If you don't want to use a closure you should use null.
	// The third argument is the host, a null host means to use the same host (the one on which this page is located on).
	// The "updateHandler" is for updates, status updates, entitlement updates.
	p = jslib.connect(operationHandler, "connectEntitlement", pushServer,updateHandler);
	
	// Setting the fields
	p.addFields(operationHandler, "addFieldsClosure",  "ClosePrice", "LastPrice", "AskPrice", "BidPrice", "AskSize", "BidSize", "Time", "Volume","LastVolume", "HighPrice", "LowPrice", "OpenPrice");
	
}

/**
 * Handles the operation results
 */
function operationHandler(closure, eventType, event, body) 
{
	if (eventType == jslib.OPERATION_ERROR) 
	{
		var err;
		switch (event) 
		{
			case jslib.ERROR_CONNECTED:
				err = "You are already connected";
				break;
			case jslib.ERROR_NOT_CONNECTED:
				err = "You are not connected";
				break;
			case jslib.ERROR_TIMEOUT:
				err = "Connection timeout";
				break;
			case jslib.ERROR_HTTP:
				err = "HTTP status error. The HTTP status is: " + body;
				break;
			case jslib.ERROR_SERVER:
				err = "Server side error: " + body;
				break;
			case jslib.ERROR_DOMAIN:
				err = "Domain error.";
				break;
			case jslib.ERROR_SERVER_DOWN:
				err = "Server down.";
				break;
		}
		alert("Error: " + closure + ", " + err);
	} 
	else if (eventType == jslib.OPERATION_OK) 
	{
		// everything is ok
	}
}

/**
 * Updates the ASK, BID, ASKSIZE and BIDSIZE fields with new content.
 * If the event type is "jslib.MESSAGE_RECEIVED" then this function received an update,
 * if the event is "jslib.MARKET_PRICE_UPDATE" it received an XML document that contains the market price update from the Migratory Push Engine server,
 * if the event is "jslib.STATUS_UPDATE" then it received an XML document with the status update.
 * For details about the structure of the XML documents, the eventTypes and events, see the Migratory Push Engine JSLIB XML Messages document.
 * The closure is always null because all the calls on this function are really asynchronous and related to the streaming connection.
 */
function updateHandler(closure, eventType, event, body) 
{
	if (eventType == jslib.STREAMING_ERROR) 
	{
		alert("Streaming error=" + event + ", body=" + body);
	} 
	else if (eventType == jslib.MESSAGE_RECEIVED) 
	{
		switch (event) 
		{
			case jslib.MARKET_PRICE_UPDATE:
				updateMarketPrice(body);
				break;
			case jslib.STATUS_UPDATE:
				updateStatus(body);
				break;
		}
	}
}

function updateMarketPrice(body) 
{	
	for (var i = 0; i < body.items.length; i++) 
	{
		var sourceType = body.items[i].source;
		var serviceName = body.items[i].service;
		var itemName = body.items[i].symbol;
		var tickername = itemName.split("_")[1];
		// We received the item "itemName" along the service "serviceName", from the source type "sourceType"
		
		for (var j = 0; j < body.items[i].fields.length; j++) 
		{	
			var fieldName = body.items[i].fields[j].name;
			var value = body.items[i].fields[j].value;
			//console.log(fieldName+"|"+value);
			// We received an update for the field "fieldName" with the value "value"				
			// Now let's update the HTML field from subscriber.html
			var object = document.getElementById(tickername + fieldName);
			if (object) 
			{
				object.innerHTML = value;
			}
		}
	}
}

function updateStatus(body) 
{
	var sourceType = body.source;
	var serviceName = body.service;
	var itemName = body.symbol;
	var itemState = body.state;
	var itemStatus = body.status;
	
	// We received a status update for the item "itemName" with service "serviceName", from the source type "sourceType"
	// The status update consists of a state "itemState" and a status "itemStatus"
	// The state is a short indicator of status, possible values are STALE, CLOSED, CLOSED_RECOVER
	// The status is a more detailed description of the state.
	msg += "Status update, source type='" + sourceType + "', item='" + serviceName + ":" + itemName + "'\nstate=" + itemState + "\nstatus=" + itemStatus + "\n\n";
	
	alert(msg);
}
function disConnect() {
    if(p != null) {
        //p.Disconnect(operationHandler,"DisconnectClosure");
    }
}
init();
var ddlSever = new Util.DropDownList($(".ddlServer")[0], function(k,v){disConnect(); pushServer=v; init()}, serverList, {triggerByClick:false, width:75,disable:false, actionAtInit:false});
</script>
</html>
